import React from 'react';
import {
  Table,
  Form,
  Input,
  Select,
  Button,
  Switch,
  Icon,
  InputNumber,
  Popconfirm,
  Tabs,
  Spin,
} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import styles from './index.less';

const Option = Select.Option;
const Item = Form.Item;

const TextArea = Input.TextArea;

@connect(state => ({
  cacheConfig: state.cacheConfig,
}))
@Form.create()
class Pages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      deviceId: null,
      formatData: null,
      currentId: null,
    };
  }

  /**
   * 获取所有设备列表
   */
  getAllDevices = () => {
    this.props.dispatch({
      type: 'cacheConfig/getAllDevices',
      payload: {},
      callback: data => {
        this.setState(
          {
            deviceId: data.id,
          },
          () => this.getCache()
        );
      },
    });
  };

  /**
   * 创建修改配置
   */
  editCache = type => {
    const {
      dispatch,
      form: { validateFieldsAndScroll },
      cacheConfig: { cache },
    } = this.props;
    const { deviceId } = this.state;
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = {};
        let method = '';
        if (type === 'add') {
          params = {
            cacheState: values.cacheState ? 1 : 0,
            denialCount: values.denialCount,
            denialTtl: values.denialTtl,
            remark: values.remark,
            successCount: values.successCount,
            successTtl: values.successTtl,
            deviceId,
          };
          method = 'cacheConfig/addCache';
        } else {
          params = {
            cacheState: values.cacheState ? 1 : 0,
            denialCount: values.denialCount,
            denialTtl: values.denialTtl,
            remark: values.remark,
            successCount: values.successCount,
            successTtl: values.successTtl,
            deviceId,
            id: cache.id,
          };
          method = 'cacheConfig/updateCache';
        }
        dispatch({
          type: method,
          payload: params,
          callback: () => {
            this.getCache();
          },
        });
      }
    });
  };

  /**
   * 根据设备查询缓存配置
   */
  getCache = () => {
    const { deviceId } = this.state;
    this.props.dispatch({
      type: 'cacheConfig/getCache',
      payload: {
        deviceId,
      },
    });
  };
  /**
   * 清除表单
   */
  clearForm = () => {
    this.props.form.resetFields();
  };

  /**
   * 筛选
   */
  select = value => {
    this.clearForm();
    this.setState(
      {
        deviceId: value,
      },
      () => this.getCache()
    );
  };

  /**
   * modal
   */
  closeModal = () => {
    this.setState({
      visible: false,
      formatData: null,
    });
  };
  //新增编辑
  updateBtn = (type = 'add', record = null) => {
    if (type === 'add') {
      this.setState({
        type: 'add',
        visible: true,
      });
    } else {
      this.setState({
        type: 'edit',
        currentId: record.id,
        visible: true,
        formatData: record,
      });
    }
  };

  /**
   * 刷新配置
   */
  freshConfig = () => {
    const { deviceId } = this.state;
    this.props.dispatch({
      type: 'cacheConfig/freshConfig',
      payload: {
        deviceId,
      },
    });
  };

  componentDidMount() {
    this.getAllDevices();
  }

  render() {
    const {
      form: { getFieldDecorator },
      cacheConfig: { allDevices, cache, confLoading },
    } = this.props;
    const { deviceId } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };

    return (
      <>
        <h3 className="head">缓存配置</h3>
        <div style={{ padding: '10px 20px' }}>
          <div>
            <span>设备:</span>
            <Select
              value={deviceId}
              onChange={this.select}
              style={{ width: '150px', marginLeft: '10px' }}
            >
              {allDevices.map(item => (
                <Option value={item.id} key={item.id}>
                  {item.deviceName}
                </Option>
              ))}
            </Select>
          </div>

          <div className={styles.wrapper}>
            <div className="mt20">
              <Spin spinning={confLoading}>
                <Form>
                  <Item {...formItemLayout} label="最大缓存数">
                    {getFieldDecorator('successCount', {
                      rules: [{ required: true, message: '不能为空' }],
                      initialValue: cache && cache.successCount,
                    })(<InputNumber style={{ width: '30%' }} />)}
                  </Item>
                  <Item {...formItemLayout} label="TTL时间">
                    {getFieldDecorator('successTtl', {
                      rules: [{ required: true, message: '不能为空' }],
                      initialValue: cache && cache.successTtl,
                    })(<InputNumber style={{ width: '30%' }} />)}
                  </Item>
                  <Item {...formItemLayout} label="否定最大缓存数">
                    {getFieldDecorator('denialCount', {
                      rules: [{ required: true, message: '不能为空' }],
                      initialValue: cache && cache.denialCount,
                    })(<InputNumber style={{ width: '30%' }} />)}
                  </Item>
                  <Item {...formItemLayout} label="否定TTL时间">
                    {getFieldDecorator('denialTtl', {
                      rules: [{ required: true, message: '不能为空' }],
                      initialValue: cache && cache.denialTtl,
                    })(<InputNumber style={{ width: '30%' }} />)}
                  </Item>
                  <Item {...formItemLayout} label="缓存状态">
                    {getFieldDecorator('cacheState', {
                      valuePropName: 'checked',
                      initialValue: cache && cache.cacheState ? true : false,
                    })(<Switch checkedChildren="开" unCheckedChildren="关" />)}
                  </Item>
                  <Item {...formItemLayout} label="备注">
                    {getFieldDecorator('remark', {
                      initialValue: cache && cache.remark,
                    })(<TextArea style={{ width: '50%' }} />)}
                  </Item>
                  <Item wrapperCol={{ offset: 6 }}>
                    {cache ? (
                      <Button type="primary" onClick={this.editCache}>
                        修改配置
                      </Button>
                    ) : (
                      <Button type="primary" onClick={() => this.editCache('add')}>
                        创建配置
                      </Button>
                    )}
                    <Button onClick={this.freshConfig} className="ml10" type="primary" icon="tool">
                      启用配置
                    </Button>
                  </Item>
                </Form>
              </Spin>
            </div>
          </div>
        </div>
      </>
    );
  }
}

export default Pages;
